package com.epro.dx.activity.creditcard;

import java.util.ArrayList;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.ChangeCountryActivity;
import com.epro.dx.activity.forgetpassword.ForgetPasswordSubmitActivity;
import com.epro.dx.activity.myaddress.EditAddressActivity;
import com.epro.dx.activity.myaddress.MyAddressBookActivity;
import com.epro.dx.activity.order.OrderPlaceActivity;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.MapUtil;
import com.google.android.gms.internal.my;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.CountryModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.StringUtil;

/**
 * 新增信用卡页面
 * */
public class BillingAddressActivity extends BaseFragmentActivity implements
		OnClickListener {

	// 使用收货地址
	private RelativeLayout useShippingAdressLayout;

	// 账单地址信息
	private String email;
	private String firstName;
	private String lastName;
	private String street1;
	private String street2;
	private String city;
	private String state;
	private String country;
	private String phone;
	private String mobile;
	private String postalCode;

	private EditText emailEt;
	private EditText firstNameEt;
	private EditText lastNameEt;
	private EditText street1Et;
	private EditText street2Et;
	private EditText cityEt;
	private EditText stateEt;
	private EditText countryEt;
	private EditText phoneEt;
	private EditText mobileEt;
	private EditText postalCodeEt;

	// 提交按钮
	private Button payButton;

	/**
	 * 国家码
	 */
	private CountryModel countryModel;
	
	private ScrollView scrollView;

	// 记录没有填写的必填项
	private int notInput = -1;
	private String[] addressItems = { "E-mail", "FirstName", "LastName",
			"Street1", "City", "State", "Country", "Phone", "PostalCode" };

	private AddressModel addressMode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_billing_address);
        Intent intent=getIntent();
        if(null!=intent){
        	addressMode=(AddressModel) intent.getSerializableExtra("AddressModel");
        }
		setTitleContent(R.string.billing_address_pagename);
		setLeftBtnContent(true, -1);

		initView();
		setEvent();
		AsyncTaskUtil.executeTask(new GetAllCountry());
		if(null!=addressMode){
        	setEditTextContent(addressMode);
        }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		sendScreen();
	}

	// 设置控件的事件️监听
	private void setEvent() {
		// 点击使用收获地址
		useShippingAdressLayout.setOnClickListener(this);
		// 点击提交按钮
		payButton.setOnClickListener(this);
		// 选择国家
		countryEt.setOnClickListener(this);
	}

	// 加载视图控件
	private void initView() {
		useShippingAdressLayout = (RelativeLayout) findViewById(R.id.creditcard_billingaddress_useshippingaddress);
        scrollView=(ScrollView) findViewById(R.id.billing_address_scroll);
		emailEt = (EditText) findViewById(R.id.creditcard_billingaddress_email);
		firstNameEt = (EditText) findViewById(R.id.address_firstname);
		lastNameEt = (EditText) findViewById(R.id.address_lastname);
		street1Et = (EditText) findViewById(R.id.address_street1);
		street2Et = (EditText) findViewById(R.id.address_street2);
		cityEt = (EditText) findViewById(R.id.address_city);
		stateEt = (EditText) findViewById(R.id.address_state);
		countryEt = (EditText) findViewById(R.id.address_country);
		phoneEt = (EditText) findViewById(R.id.address_phone);
		mobileEt = (EditText) findViewById(R.id.address_mobile);
		postalCodeEt = (EditText) findViewById(R.id.address_postal_code);

		payButton = (Button) findViewById(R.id.address_save_btn);
		payButton.setText(R.string.billing_address_btname);
		
		//设置Email为用户注册时的邮箱
		String email = StringUtil.getConfig(BillingAddressActivity.this, ServerConstant.Parameter.PARAMETER_NAME_USER_EMAIL);
		if(!TextUtils.isEmpty(email)){
			emailEt.setText(email);
		}

	}

	/**
	 * 设置页面相关信息
	 * 
	 * @param addModel
	 */
	private void setEditTextContent(AddressModel addModel) {
		AddressModel.Address myAddress = addModel.getAddress();
		if (null != myAddress) {
			firstNameEt.setText(myAddress.getFirstName());
			lastNameEt.setText(myAddress.getLastName());
			street1Et.setText(myAddress.getStreet1());
			street2Et.setText(myAddress.getStreet2());
			cityEt.setText(myAddress.getCity());
			stateEt.setText(myAddress.getState());
			SharedPreferences share = getSharedPreferences("countryData",
					MODE_PRIVATE);
			String str = share.getString(myAddress.getCountryCode() + "",
					myAddress.getCountryCode() + "");
			countryEt.setText(str);
			phoneEt.setText(myAddress.getPhoneNumber());
			mobileEt.setText(myAddress.getMobile());
			postalCodeEt.setText(myAddress.getPostalCode());
			String uEmail=myAddress.getEmail();
			if(null!=uEmail&&!"".equals(uEmail)){
				emailEt.setText(uEmail);
			}
		}

	}

	private boolean checkAddress() {
		email = emailEt.getText().toString();
		if (TextUtils.isEmpty(email)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_email_null, emailEt);
			return false;
		}
		if (!StringUtil.isEmail(email)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_email_error, emailEt);
			return false;
		}
		if (email.length() < Constant.Rule.EMAIL_MIN_LENGTH
				|| email.length() > Constant.Rule.TEXT_MAX_LENGTH) {
			AlertToast.alert(
					BillingAddressActivity.this,
					getString(R.string.user_register_username_validate_length,
							Constant.Rule.EMAIL_MIN_LENGTH,
							Constant.Rule.TEXT_MAX_LENGTH), emailEt);
			return false;
		}
		firstName = firstNameEt.getText().toString().trim();
		if (TextUtils.isEmpty(firstName)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_firstname_null, firstNameEt);
			return false;
		}
		if (!StringUtil.isFirstnameOrLastname(firstName)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_firstname_format_error,
					firstNameEt);
			return false;
		}
		if (firstName.length() < Constant.Rule.USERNAME_MIN_LENGTH
				|| firstName.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
			AlertToast.alert(
					BillingAddressActivity.this,
					getString(R.string.user_register_firstname_validate_length,
							Constant.Rule.USERNAME_MIN_LENGTH,
							Constant.Rule.FIRORLASNAME_MAX_LEN), firstNameEt);
			return false;
		}
		// lastname 校验
		lastName = lastNameEt.getText().toString().trim();
		if (TextUtils.isEmpty(lastName)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_lastname_null, lastNameEt);
			return false;
		}
		if (!StringUtil.isFirstnameOrLastname(lastName)) {
			AlertToast.alert(BillingAddressActivity.this,
					R.string.user_register_title_lastname_format_error,
					lastNameEt);
			return false;
		}
		if (lastName.length() < Constant.Rule.USERNAME_MIN_LENGTH
				|| lastName.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
			AlertToast.alert(
					BillingAddressActivity.this,
					getString(R.string.user_register_lastname_validate_length,
							Constant.Rule.USERNAME_MIN_LENGTH,
							Constant.Rule.FIRORLASNAME_MAX_LEN), lastNameEt);
			return false;
		}

		street1 = street1Et.getText().toString().trim();
		if (TextUtils.isEmpty(street1)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Street1 ");
			AlertToast
					.alert(BillingAddressActivity.this, suggestStr, street1Et);
			return false;
		}

		street2 = street2Et.getText().toString().trim();
		// if (TextUtils.isEmpty(street2)) {
		// String suggestStr = getResources().getString(
		// R.string.user_address_null, " Street2 ");
		// AlertToast.alert(BillingAddressActivity.this, suggestStr, street2Et);
		// return false;
		// }

		city = cityEt.getText().toString().trim();
		if (TextUtils.isEmpty(city)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " City ");
			AlertToast.alert(BillingAddressActivity.this, suggestStr, cityEt);
			return false;
		}
		state = stateEt.getText().toString().trim();
		if (TextUtils.isEmpty(state)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " State ");
			AlertToast.alert(BillingAddressActivity.this, suggestStr, stateEt);
			return false;
		}
		country = countryEt.getText().toString().trim();
		if (!"".equals(country) && null != country && null != countryModel) {
			country = (String) MapUtil.getKeyByValue(
					countryModel.getAllCountry(), country).get(0);
		}
		if (TextUtils.isEmpty(country)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Country ");
			AlertToast
					.alert(BillingAddressActivity.this, suggestStr, countryEt);
			return false;
		}
		phone = phoneEt.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Phonenumber ");
			AlertToast.alert(BillingAddressActivity.this, suggestStr, phoneEt);
			return false;
		}
		postalCode = postalCodeEt.getText().toString().trim();
		if (TextUtils.isEmpty(postalCode)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " PostalCode ");
			AlertToast.alert(BillingAddressActivity.this, suggestStr,
					postalCodeEt);
			return false;
		}

		mobile = mobileEt.getText().toString().trim();

		return true;

	}

	/**
	 * 获取请求对象
	 * 
	 * @param addressModel
	 * @param isAddAddress
	 *            是否为新增地址
	 * @return
	 */
	private AddressModel getNewAddressModel() {
		AddressModel newaddAddressModel = new AddressModel();
		AddressModel.Address address = new AddressModel.Address();

		long customerId = ActivityUtil.getCustomerID();
		if(null!=addressMode){
			newaddAddressModel.setAddressID(addressMode.getAddressID());
		}
		newaddAddressModel.setCustomerID(customerId);
		newaddAddressModel.setAddressType(1);
		newaddAddressModel.setCountryName(country);
		address.setFirstName(firstName);
		address.setLastName(lastName);
		address.setCountry(country);
		address.setCountryCode(country);
		address.setState(state);
		address.setCity(city);
		address.setStreet1(street1);
		address.setStreet2(street2);
		address.setPostalCode(postalCode);
		address.setPhone(phone);
		address.setPhoneNumber(phone);
		address.setMobile(mobile);
		address.setEmail(email);
		newaddAddressModel.setAddress(address);
		return newaddAddressModel;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == ServerConstant.Parameter.CHOOSE_ADDRESS_CODE
				&& data != null) {
			AddressModel addModel = (AddressModel) data
					.getSerializableExtra("addressModel");
			addressMode=addModel;
			setEditTextContent(addModel);
		}
		if (resultCode == ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE) {
			countryEt.setText(data.getStringExtra("countryName"));
			if (null == countryModel) {
				countryModel = (CountryModel) data
						.getSerializableExtra("countryModel");
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.creditcard_billingaddress_useshippingaddress:// 跳转到收货地址列表页
			Intent i = new Intent(BillingAddressActivity.this,
					MyAddressBookActivity.class);
			i.putExtra("fromChooseAdd", true);
			if(null!=addressMode){
				i.putExtra("ChooseAddressID", addressMode.getAddressID());
			}
			startActivityForResult(i,
					ServerConstant.Parameter.CHOOSE_ADDRESS_CODE);
			break;
		case R.id.address_save_btn:// 执行提交使用账单地址逻辑
			if (checkAddress()) {
				Intent intent = new Intent();
				AddressModel newAddress = getNewAddressModel();
				intent.putExtra("addressModel", newAddress);
				setResult(1, intent);
				finish();
			}

			break;
		case R.id.address_country:// 跳转到选择国家列表页面
			Bundle bundle = new Bundle();
			// bundle.putStringArrayList("listCountry", listCountry);
			Intent intent = new Intent(this, ChangeCountryActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent,
					ServerConstant.Parameter.CHANGE_COUNTRY_REQUESTCODE);
			break;

		default:
			break;
		}
	}

	/**
	 * 获取用户收货地址
	 * 
	 * @author hf
	 * @version [版本号, 2015-8-4]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	class GetAllCountry extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				if (null != BaseFragmentActivity.countryPreferences
						&& !BaseFragmentActivity.countryPreferences.getAll()
								.isEmpty()) {
					countryModel = new CountryModel();
					countryModel
							.setAllCountry(BaseFragmentActivity.countryPreferences
									.getAll());
				} else {
					// FIXME 该部分代码需要优化
					if (null == countryPreferences) {
						countryPreferences = getSharedPreferences(
								"countryData", MODE_PRIVATE);
					}
					countryModel = ProviderFactory.createUserServiceProvider()
							.allCountry();
					BaseFragmentActivity.persistenceCountry(countryModel
							.getAllCountry());
				}
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
                return "exception";
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
                if("0".equals(result)){
                	hideAllLayout(scrollView);
                }else{
                	hideAllLayout();
                	AlertToast.alert(BillingAddressActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
		}
	}

}
